{% extends 'base.html' %}
{% load seahub_tags i18n %}

{% block sub_title %}{{u_filename}} - {% endblock %}

{% block extra_style %}
{% if filetype == 'Text' %}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}codemirror/codemirror.css" />
<style type="text/css">
.CodeMirror pre.CodeMirror-cursor { overflow:hidden; } /* for chrome */
.CodeMirror-focused pre.CodeMirror-cursor { visibility: visible; }
.CodeMirror-scroll { height:auto; min-height:700px; }
</style>
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}codemirror/monokai.css" />
{% endif %}
{% if filetype == 'Markdown' %}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/editormd.min.css" />
<style type="text/css">
#main {
    min-height:0;
}
.editormd,
.editormd .CodeMirror {
    font-family: inherit;
}
.editormd {
    margin:0 auto;
}
/* for 'link', 'image', 'table' popups */
.editormd-form input[type=text],
.editormd-form input[type=number] {
    height:auto;
    border-radius:4px;
    margin:0;
    box-sizing: border-box;
}
</style>
{% endif %}
<style type="text/css">
#header {
    display:none;
}
#path-op {
    box-sizing:content-box;
    width:950px;
    margin:0 auto 6px;
}
#path-op .path {
    margin-top:1.2em
}
#file-edit {
    min-height:700px;
    padding:30px 0 60px;
    background:#f4f4f4;
    border-top:1px solid #ededed;
}
#edit-tip {
    box-shadow:0 0 6px #ccc;
    border:1px solid #ccc;
    margin:0 auto;
}
#edit-tip {
    min-height:200px;
    padding:10px;
    width:928px;
    background:#fff;
    margin:0 auto;
}
.fixed-path-op {
    position:fixed;
    left:0;
    top:0;
    background:#fff;
    border-bottom:1px solid #ededed;/*for ie*/
    box-shadow:0 1px 3px #777;
    z-index:1010;/*make seaf image show below path-op*/
}
.CodeMirror {
    width:950px;
    margin:0 auto;
    box-shadow:0 0 6px #272822;
}
</style>
{% endblock %}

{% block main_panel %}
    <div id="path-op" class="ovhd">
         <p class="path fleft">
         {% trans "Current path: " %}
         {% for name, link in zipped %}
            {% if not forloop.last %}
            <a href="{{ SITE_ROOT }}#common/lib/{{ repo.id }}/{{ link|strip_slash }}">{{ name }}</a> /
            {% else %}
                <a href="{% url 'view_lib_file' repo.id path %}" target="_blank">{{ name }}</a>
            {% endif %}
         {% endfor %}
         </p>
         <div id="op-after-edit" class="fright vh">
             <span id="saved-tip" class="tip hide">{% trans "Draft saved." %}</span>
             <button id="file-edit-submit">{% trans "Submit" %}</button>
             <a href="{{cancel_url}}" id="file-edit-cancel">{% trans "Cancel" %}</a>
         </div>
    </div>
    <div id="file-edit">
        {% include 'snippets/file_encoding.html' %}
        {% if err %}
            <div id="edit-tip" class="article">
                <p class="error">{{ err }}</p>
            </div>
        {% else %}
            {% if file_content != None %}
                {% if filetype == 'Text' %}
                <textarea id="docu-view" class="hide">{{ file_content|escape }}</textarea>
                {% endif %}

                {% if filetype == 'Markdown' %}
                <div id="md-editor">
                    <textarea class="hide">{{ file_content|escape }}</textarea>
                </div>
                {% endif %}

            {% endif %}
        {% endif %}
    </div>

    {% if not err and repo.encrypted %}
    <form id="repo-decrypt-form" class="hide" action="" method="post">
        <h3 id="dialogTitle">{% trans 'Library' %} <span class="op-target">{{repo.name}}</span> {% trans 'is encrypted' %}</h3>
        <label for="passwd">{% trans 'Password' %}</label><br />
        <input type="password" name="password" class="input" id="passwd" />
        <p class="tip">{% trans "The password will be kept in the server for only 1 hour." %}</p>
        <p class="error hide"></p>
        <input type="submit" class="submit" value="{% trans 'Submit' %}" />
    </form>
    {% endif %}


    {% if not err and filetype == 'Markdown' %}
    <form id="add-file-form" action="" method="post" class="file-choose-form hide">{% csrf_token %}
        <h3>{% trans "Choose a file" %}</h3>
        <div class="dir-tree-cont">
            <div id="repos-dirs">
                <span class="loading-icon loading-tip"></span>
            </div>
        </div>
        <input type="hidden" name="dst_repo" value="" />
        <input type="hidden" name="dst_path" value="" />
        <p class="error hide">{% trans "Please choose a file." %}</p>
        <button type="submit" class="submit">{% trans "Submit" %}</button>
        <button class="simplemodal-close">{% trans "Cancel" %}</button>
    </form>

    {% endif %}

    <div id="load-draft" class="hide">
        <h3 id="dialogTitle">{% trans "Draft Available" %}</h3>
        <p>{% trans "There's a saved draft for this file, would you like to load it?" %}</p>
        <button id="load-draft-btn">{% trans "Load" %}</button>
        <button class="simplemodal-close" id="discard-draft-btn">{% trans "Discard" %}</button>
    </div>
{% endblock %}

{% block extra_script %}
{% if not err and file_content != None %}
<script type="text/javascript">
if ('localStorage' in window && window['localStorage'] !== null) {
    var browserStorage = {
        set : function(key, value) {
            try {
                localStorage.setItem(key, value + "");
            } catch (e) {
                feedback("{% trans "Failed to save draft, exceeded max quota" %}", 'error');
            }
        },
        get : function(key) {
            return localStorage.getItem(key);
        },
        remove : function(key) {
            localStorage.removeItem(key);
        }
    };

    var key = '{{repo.id}}_{{path}}_draft';

    var saved_draft = browserStorage.get(key);
    if (saved_draft) {
        $('#load-draft').modal();
        $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
    }
}
</script>

{% if filetype == 'Text' %}
<script type="text/javascript" src="{{MEDIA_URL}}codemirror/codemirror-2.36.js"></script>
{% endif %}

{% if filetype == 'Markdown' %}
<script type="text/javascript" src="{{MEDIA_URL}}js/editormd.min.js"></script>
{% endif %}

{% endif %}
<script type="text/javascript">
{% if not err and file_content != None %}
// make '#path-op' fixed when scroll
$(window).on('scroll', function() {
    var $path = $('#path-op');
    var $edit = $('#file-edit');
    var offset = ($(window).width() - parseInt($path.css('width')))/2;
    if ($(window).scrollTop() > 0) {
        $edit.css('margin-top', $path.outerHeight(true));
        $path.addClass('fixed-path-op').css({'padding-left':offset, 'padding-right':offset});
    } else {
        $path.removeClass('fixed-path-op').removeAttr('style');
        $edit.css('margin-top', 0);
    }
});

if ('localStorage' in window && window['localStorage'] !== null) {

    var saved_tip = $('#saved-tip');
    function saveDraft() {
        var draft;
        {% if filetype == 'Text' %}
        draft = editor.getValue();
        {% endif %}
        {% if filetype == 'Markdown' %}
        draft = mdEditor.getMarkdown();
        {% endif %}
        browserStorage.set(key, draft);
        saved_tip.removeClass('hide');
    }

    $('#load-draft-btn').on('click', function() {
        $.modal.close();
        {% if filetype == 'Text' %}
        editor.setValue(saved_draft);
        {% endif %}
        {% if filetype == 'Markdown' %}
        mdEditor.setMarkdown(saved_draft);
        {% endif %}
        feedback("{% trans "Draft successfully loaded" %}", 'success', 1000);
    });

    $('#discard-draft-btn, #file-edit-cancel').on('click', function() {
        browserStorage.remove(key);
    });
}

{% if filetype == 'Text' %}
var editor = CodeMirror.fromTextArea($('#docu-view')[0], {
    {% include "snippets/editor_set_mode.html" %}
    theme: 'monokai',
    indentUnit: 4,
    lineNumbers: true,
    lineWrapping: true,
    onCursorActivity: function() {
        var cursor = editor.cursorCoords(true, 'page');
        if (cursor.yBot >= $(window).height() + $(window).scrollTop() - 60) {
           $(window).scrollTop($(window).scrollTop() + parseInt($('#file-edit').css('padding-bottom')));
        }
        // keep the cursor visible when path-op fixed and moving the cursor upward
        if (cursor.y - $(window).scrollTop() < $('#path-op').outerHeight() && !editor.somethingSelected()) {
            $(window).scrollTop(cursor.y - $('#path-op').outerHeight());
        }
    },
    autofocus: true,
    onKeyEvent: function(instance, event) {
        if (event.type == 'keyup') {
            if ('localStorage' in window && window['localStorage'] !== null) {
                saveDraft();
            }
        }
    }
});
{% endif %}

{% if filetype == 'Markdown' %}
var $fileEdit = $('#file-edit');
var pathOpHeight = $('#path-op').outerHeight(true),
    fileEncContHeight = $('#file-enc-cont').outerHeight(true);
$fileEdit.css({'min-height':0, 'padding':'30px 0'}).outerHeight($(window).height() - pathOpHeight);
var mdEditor = editormd('md-editor', {
    width: 950,
    height: $fileEdit.height() - fileEncContHeight - 2,
    onresize: function () { // window resize
        var $mdEditor = this.editor;
        if (this.state.fullscreen) {
            $mdEditor.height('100%');
        } else {
            $fileEdit.outerHeight($(window).height() - pathOpHeight);
            $mdEditor.height($fileEdit.height() - fileEncContHeight - 2);
        }
    },
    onfullscreenExit: function () {
        this.resize();
    },
    path: '{{MEDIA_URL}}js/editormd/lib/', // 'lib' path

    placeholder: '', // for empty file
    gotoLine: false, // disable gotoLine
    searchReplace: false, // disable 'search and Replace'
    toc: false, // Table of contents
    pageBreak: false, // disable parse page break [========]
    atLink: false, // for @link
    previewCodeHighlight: false,
    showTrailingSpace: false,
    matchWordHighlight: false,

    toolbarIcons: function () {
        // custom toolbar
        return [
            'bold', 'italic', '|',
            'h1', 'h2', 'h3', 'h4', '|',
            'list-ul', 'list-ol', 'hr', '|',
            'link', 'file', 'image', 'table', '|',
            'undo', 'redo','|',
            'watch', 'fullscreen'
        ];
    },
    toolbarIconsClass: {
       'file': 'fa-file'
    },
    toolbarHandlers: {
        'file': function(cm, icon, cursor, selection) {
            var $form = $('#add-file-form');
            $form.modal();
            $('#simplemodal-container').css({'width':'auto', 'height':'auto'});

            // fetch repos and render the tree
            $.ajax({
                url: '{% url 'api2-repos' %}',
                cache: false,
                dataType: 'json',
                success: function(data) {
                    var repos = [], repo_ids = [], repo;
                    for (var i = 0, len = data.length; i < len; i++) {
                        repo = data[i];
                        // remove encrypted & duplicate
                        if (!repo.encrypted && repo_ids.indexOf(repo.id) == -1) {
                            repo_ids.push(repo.id);
                            repos.push({
                                'text': HTMLescape(repo.name),
                                'data': {'repo_id': repo.id, 'path': '/'},
                                'children': true
                            });
                        }
                    }
                    repos.sort(function(a, b) {
                        var a_name = a.text.toLowerCase();
                        var b_name = b.text.toLowerCase();
                        return a_name < b_name ? -1 : 1;
                    });
                    FileTree.renderTree($('#repos-dirs').data('site_root', '{{SITE_ROOT}}'), $form, repos);  // there is at least 1 repo
                },
                error: function(xhr) {
                    if (xhr.responseText) {
                        feedback(JSON.parse(xhr.responseText).error||JSON.parse(xhr.responseText).error_msg, 'error');
                    } else {
                        feedback("{% trans "Please check the network." %}", 'error');
                    }
                }
            });

            $form.on('submit', function() {
                var dst_repo = $('[name="dst_repo"]', $form).val(),
                    dst_path = $('[name="dst_path"]', $form).val();

                // no item is selected
                if (!dst_repo || !dst_path) {
                    $('.error', $form).removeClass('hide');
                    return false;
                }

                // a dir is selected
                if (dst_path.charAt(dst_path.length - 1) == '/') {
                    $('.error', $form).removeClass('hide'); // only a file can be selected
                    return false;
                }

                $.modal.close();

                var path_arr = dst_path.split('/'),
                    path_arr_ = [],
                    name = path_arr[path_arr.length - 1],
                    encodedPath;
                for (var i = 0, len = path_arr.length; i < len; i++) {
                    path_arr_.push(encodeURIComponent(path_arr[i]));
                }
                encodedPath = path_arr_.join('/');

                var url = '{{SITE_ROOT}}lib/' +  dst_repo + '/file' + encodedPath;
                // replace ... or directly insert
                cm.replaceSelection('[' + name + '](' + url + ')');

                return false;
            });

        }
    },
    lang: {
        // custom title of toolbar icons
        toolbar: {
            bold: "{% trans "Bold" %}",
            italic: "{% trans "Italic" %}",
            h1: "{% trans "Heading 1" %}",
            h2: "{% trans "Heading 2" %}",
            h3: "{% trans "Heading 3" %}",
            h4: "{% trans "Heading 4" %}",
            'list-ul': "{% trans "Unordered list" %}",
            'list-ol': "{% trans "Ordered list" %}",
            hr: "{% trans "Horizontal rule" %}",
            link: "{% trans "Link" %}",
            "file": "{% trans "File" %}",
            image: "{% trans "Image" %}",
            table: "{% trans "Table" %}",
            undo: "{% trans "Undo(Ctrl+Z)" %}",
            redo: "{% trans "Redo(Ctrl+Y)" %}",
            watch: "{% trans "Close live preview" %}",
            unwatch: "{% trans "Live preview" %}",
            fullscreen: "{% trans "Fullscreen" %}"
        },
        // buttons in popups
        buttons: {
            enter: "{% trans "Submit" %}",
            cancel: "{% trans "Cancel" %}",
            close: "{% trans "Close" %}"
        },
        dialog: {
            link: {
                title: "{% trans "Link" %}",
                url: "URL",
                urlTitle: "{% trans "Title" %}",
                urlEmpty: "{% trans "Please enter URL." %}"
            },
            image: {
                title: "{% trans "Image" %}",
                url: "URL",
                alt: "{% trans "Title" %}",
                imageURLEmpty: "{% trans "Please enter URL." %}"
            },
            table: {
                title: "{% trans "Table" %}",
                cellsLabel: "{% trans "Cells" %}",
                alignLabel: "{% trans "Align" %}",
                rows: "{% trans "Rows" %}",
                cols: "{% trans "Columns" %}",
                aligns: ["{% trans "Default" %}", "{% trans "Align left" %}", "{% trans "Align center" %}", "{% trans "Align right" %}"]
            }
        }
    },

    onchange: saveDraft
});
{% endif %}

$('#op-after-edit').removeClass('vh');

$('#file-edit-submit').on('click', function() {
    disable($(this));
    editSubmit();
});
function editSubmit() {
    {% if filetype == 'Text' %}
    var content = editor.getValue();
    {% endif %}
    {% if filetype == 'Markdown' %}
    var content = mdEditor.getMarkdown();
    {% endif %}

    $.ajax({
        type: "POST",
        url: '{{ SITE_ROOT }}repo/{{repo.id}}/file/edit/?p={{path|urlencode}}&head={{head_id}}&from={{from}}&gid={{gid}}&wiki_slug={{wiki_slug}}',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {content: content, encoding: $('#file-enc').val()},
        success: function(data) {
            if ('localStorage' in window && window['localStorage'] !== null) {
                browserStorage.remove(key);
            }
            location.href = data['href'];
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.responseText) {
                var resp = JSON.parse(xhr.responseText);
                feedback(resp['error'], 'error');
                if (resp['op'] == 'decrypt') {
                    $('#repo-decrypt-form').modal();
                    $('#simplemodal-container').css({'height':'auto'});
                }
            } else {
                feedback("{% trans "Submit failed. Please check the network." %}", 'error');
            }
            enable($('#file-edit-submit'));
        }
    });
}
{% endif %}

{% if op == 'decrypt' %}
$('#repo-decrypt-form').modal();
$('#simplemodal-container').css({'height':'auto'});
{% endif %}

$('#repo-decrypt-form').on('submit', function() {
    var $form = $(this);
    var $pwd_input = $('input[name="password"]', $form);
    var pwd = $.trim($pwd_input.val());
    var $error = $('.error', $form);

    if (!pwd) {
        $error.html("{% trans "Password is required." %}").removeClass('hide');
        return false;
    }

    var $submitBtn = $('[type="submit"]', $form);
    disable($submitBtn);
    $.ajax({
        url: '{% url 'api-v2.1-repo-set-password' repo.id %}',
        type: 'POST',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {
            password: pwd
        },
        success: function(data) {
            if (data['success']) {
                $.modal.close();
                {% if file_content != None %}
                editSubmit();
                {% endif %}
                {% if op == 'decrypt' %}
                location.reload(true);
                {% endif %}
            }
        },
        error: function(xhr) {
            var err = '';
            if (xhr.responseText) {
                err = JSON.parse(xhr.responseText).error_msg;
            } else {
                err = "{% trans "Failed. Please check the network." %}";
            }
            $error.html(err).removeClass('hide');
            enable($submitBtn);
        }
    });
    return false;
});

</script>
{% endblock %}
